import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { defalutImg } from '../../../../comm';
import { PermissionService } from '../../../../service/permission.service';
import { CommonService } from '../../../../services-common/common.service';
import { RentClassManageService } from '../rent-class-manage.service';

@Component({
  selector: 'app-rent-plan-class',
  templateUrl: './rent-plan-class.component.html',
  styleUrls: ['./rent-plan-class.component.scss']
})
export class RentPlanClassComponent implements OnInit {

  fallbackImg: string = defalutImg;

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 跳转方式
  typeSet: any = { 1: '商品ID', 2: '链接', 3: '搜索', 4: '分类' };
  // 上级分类 (一级、二级)
  superiorOptions: Array<any> = [];

  /**
   * 一级分类Modal
   * ----------------------------------------------------------------
   */
  isOneVisible = false;
  oneClassItem: any = null;
  subOneLoading = false;
  validateOneForm!: FormGroup;

  /**
   * 二级分类Modal
   * ----------------------------------------------------------------
   */
   isTwoVisible = false;
   twoClassItem: any = null;
   subTwoLoading = false;
   validateTwoForm!: FormGroup;

   /**
   * 三级分类Modal
   * ----------------------------------------------------------------
   */
  isThreeVisible = false;
  threeClassItem: any = null;
  subThreeLoading = false;
  validateThreeForm!: FormGroup;
  classTreeChecked: boolean = false;

  /**
   * ----------------------------------------------------------------
   * 关联商品
   * ----------------------------------------------------------------
   */
  // 关联商品 Modal
  isRelationVisible: boolean = false;
  relationGoodType: number = 0;
  relationGoodItem: any = null;
  goodTableParams: any = {
    loading: false,
    page: 1,
    pageSize: 10,
    total: 0,
    title: '' // 商品标题
  };
  goodTable: any = [];
  subRelationGoodLoading: boolean = false;
  // 关联商品 勾选
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  /**
   * ----------------------------------------------------------------
   * 商品勾选 Table
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id)) && this.listOfCurrentPageData.length > 0;
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private nzModal: NzModalService,
    public permission: PermissionService,
    private commonService: CommonService,
    private services: RentClassManageService
  ) { }

  ngOnInit(): void {
    // 一级分类Forms
    this.validateOneForm = this.fb.group({
      name: ['', [Validators.required]], // 名称
      sort: [''], // 排序
      topImg: [''], // 顶部图片
      icon: ['', [Validators.required]], // 图标
      url: [''], // 链接
      // params: [''], // 链接参数
      status: [1, [Validators.required]] // 状态 0：禁用 1：启用
    });

    // 二级分类Forms
    this.validateTwoForm = this.fb.group({
      pid: ['', [Validators.required]], // 上级分类
      name: ['', [Validators.required]], // 名称
      sort: [''], // 排序
      status: [1, [Validators.required]] // 状态 0：禁用 1：启用
    });

    // 级分类Forms
    this.validateThreeForm = this.fb.group({
      pid: ['', [Validators.required]], // 上级分类
      name: ['', [Validators.required]], // 名称
      sort: ['', [Validators.required]], // 排序
      icon: ['', [Validators.required]], // 图标
      url: [''], // 链接
      // params: ['', [Validators.required]], // 链接参数
      status: [1, [Validators.required]] // 状态 0：禁用 1：启用
    });

    this.loadTable();
  }

  async loadTable() {
    let params = {
      pageNum: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getRentPlaneList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      const {records, total} = data || {};
      if (records.length) {
        records.forEach((ele: any) => {
          ele.isShow = true;

          if (ele.list && ele.list.length) {
            ele.list.map((m: any) => m.isShow = true);
          }
        });
      }

      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.msg.error(message);
    }
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  async onTableDelete(item: any) {
    let params = {
      id: item.id,
      status: 2
    };
    const {code, data, message}: any = await this.services.deteleClassData(params);
    if (code === 0) {
      this.msg.success('删除成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 查询上级分类列表
   * @param type 1：一级分类 2：二级分类
   */
  async loadSuperiorClassData(type: number) {
    const {code, data, message}: any = await this.services.getSuperiorClassList(type);
    if (code === 0) {
      this.superiorOptions = data || [];
    } else {
      this.superiorOptions = [];
      this.msg.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 一级分类Modal
   * 0：新增 1：编辑
   * ----------------------------------------------------------------
   */
  showClassOneModal(type: number, item?: any) {
    this.oneClassItem = item ? item : null;
    this.validateOneForm.reset();
    if (type === 1) {
      this.validateOneForm.patchValue({
        name: item.name || '', // 名称
        sort: item.sort || '', // 排序
        topImg: item.topImg || '', // 顶部图片
        icon: item.icon || '', // 图标
        url: item.url || '', // 链接
        status: item.status // 状态 0：禁用 1：启用
      });
    } else {
      this.validateOneForm.get('status')?.setValue(1);
    }
    this.isOneVisible = true;
  }

  async subClassOneData() {
    if (this.validateOneForm.valid) {
      let params: any = {
        ...this.validateOneForm.value,
        level: 1 // 一级
      }
      for (let key in params) {
        if (this.commonService.isEmpty(params[key])) {
          params[key] = '';
        }
      }

      if (!this.commonService.isEmpty(this.oneClassItem)) {
        params.id = this.oneClassItem.id;
      }
      // return
      this.subOneLoading = true;
      await this.subInterface(params);
      this.subOneLoading = false;
    } else {
      Object.values(this.validateOneForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 二级分类Modal
   * 0：新增 1：编辑
   * ----------------------------------------------------------------
   */
  showClassTwoModal(type: number, item?: any) {
    this.loadSuperiorClassData(1);

    this.twoClassItem = item ? item : null;
    this.validateTwoForm.reset();
    if (type === 1) {
      this.validateTwoForm.patchValue({
        pid: item.pid, // 上级分类
        name: item.name || '', // 名称
        sort: !this.commonService.isEmpty(item.sort) ? item.sort : '', // 排序
        status: item.status // 状态 0：禁用 1：启用
      })
    } else {
      this.validateTwoForm.get('status')?.setValue(1);
    }
    this.isTwoVisible = true;
  }

  async subClassTwoData() {
    if (this.validateTwoForm.valid) {
      let params: any = {
        ...this.validateTwoForm.value,
        level: 2 // 二级
      }
      for (let key in params) {
        if (this.commonService.isEmpty(params[key])) {
          params[key] = '';
        }
      }

      if (!this.commonService.isEmpty(this.twoClassItem)) {
        params.id = this.twoClassItem.id;
      }
      // return
      this.subTwoLoading = true;
      await this.subInterface(params);
      this.subTwoLoading = false;
    } else {
      Object.values(this.validateTwoForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 三级分类Modal
   * 0：新增 1：编辑
   * ----------------------------------------------------------------
   */
  showClassThreeModal(type: number, item?: any) {
    this.loadSuperiorClassData(2);

    this.threeClassItem = item ? item : null;
    this.validateThreeForm.reset();
    if (type === 1) {
      this.validateThreeForm.patchValue({
        pid: item.pid, // 上级分类
        name: item.name || '', // 名称
        sort: !this.commonService.isEmpty(item.sort) ? item.sort : '', // 排序
        icon: item.icon || '', // 图标
        url: item.url || '', // 链接
        status: item.status // 状态 0：禁用 1：启用
      });
      this.classTreeChecked = item.type === 4 ? true : false;

      // 设置链接是否禁用
      if (item.type === 4) {
        this.validateThreeForm.controls.url.disable();
      } else {
        this.validateThreeForm.controls.url.enable();
      }
    } else {
      this.validateThreeForm.get('status')?.setValue(1);
    }
    this.isThreeVisible = true;
  }

  classThreeCheckChange(val: boolean) {
    if (val) {
      this.validateThreeForm.patchValue({
        url: ''
      });
      // 设置三级分类(链接)禁用
      this.validateThreeForm.controls.url.disable();
    } else {
      // 设置三级分类(链接)可用
      this.validateThreeForm.controls.url.enable();
    }
  }

  async subClassThreeData() {
    if (this.validateThreeForm.valid) {
      let params: any = {
        ...this.validateThreeForm.value,
        type: this.classTreeChecked ? 4 : '', // 是否勾选分类
        level: 3 // 三级
      }

      for (let key in params) {
        if (this.commonService.isEmpty(params[key])) {
          params[key] = '';
        }
      }
      if (!this.commonService.isEmpty(this.threeClassItem)) {
        params.id = this.threeClassItem.id;
      }
      // return
      this.subThreeLoading = true;
      await this.subInterface(params);
      this.subThreeLoading = false;
    } else {
      Object.values(this.validateThreeForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // 新增 | 编辑interface
  async subInterface(params: any) {
    // 0：新增api 1：编辑api
    let apiType = params.id ? 1 : 0;
    const {code, message}: any = await this.services.editClassItemData(params, apiType);
    
    if (code === 0) {
      this.isOneVisible = false;
      this.isTwoVisible = false;
      this.isThreeVisible = false;

      this.msg.success('操作成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 关联 | 移除商品
   * ----------------------------------------------------------------
   */
  // 查询商品
  async getGoodsList() {
    const { thirdItem } = this.relationGoodItem || {};
    let params = {
      goods: this.goodTableParams.title,
      operationType: thirdItem.id, // 类型ID(三级ID)
      delete: this.relationGoodType, // 0表示正常 1表示移除
      page: this.goodTableParams.page,
      pageSize: this.goodTableParams.pageSize
    }
    const res: any = await this.services.getRentGoodsListData(params);
    
    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.goodTable = records || [];
      this.goodTableParams.total = total || 0;
    } else {
      this.msg.error(res.message);
    }
  }
  // PageIndex Change
  goodIndexChange(index: number) {
    this.goodTableParams.page = index;
    this.getGoodsList();
  }
  // PageSize Change
  goodSizeChange(sizeNum: number) {
    this.goodTableParams.page = 1;
    this.goodTableParams.pageSize = sizeNum;
    this.getGoodsList();
  }

  searchGoodTable() {
    this.goodTableParams.page = 1;
    this.getGoodsList();
  }
  resetGoodTable() {
    this.goodTableParams.title = '';
    this.goodTableParams.page = 1;
    this.getGoodsList();
  }

  showRelationGoodsModal(item: any, type: number) {
    this.relationGoodItem = item;
    this.relationGoodType = type;
    this.setOfCheckedId.clear();

    this.goodTableParams.page = 1;
    this.getGoodsList();
    this.isRelationVisible = true;
  }

  relationCancel() {
    this.isRelationVisible = false;
  }

  subRelationData() {
    const { thirdItem } = this.relationGoodItem || {};
    this.nzModal.confirm({
      nzTitle: `${this.relationGoodType === 0 ? '关联' : '移除'}提示`,
      nzContent: `确认将<b>${this.setOfCheckedId.size}</b>个商品${this.relationGoodType === 0 ? '关联到' : '移除于'}<b>(${thirdItem?.name})</b>分类下?`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.subbRelationInterface();
      },
      nzCancelText: '取消'
    });
  }

  async subbRelationInterface() {
    const {firetItem, secondItem, thirdItem} = this.relationGoodItem || {};
    let tempArrs: any = []; // 对象数组 [{"id":商品id,"type":分类id}]
    Array.from(this.setOfCheckedId).forEach((id: any) => {
      tempArrs.push({
        id: id, // 商品ID
        firstType: firetItem.id, // 一级分类id
        secondType: secondItem.id, // 二级分类id
        thirdType: thirdItem.id // 三级分类id
      })
    });
    
    let params = {
      delete: this.relationGoodType, // 是否是批量删除 0、添加 1、删除 [关联 | 移除]
      list: tempArrs
    }
    // return
    
    this.subRelationGoodLoading = true;
    const res: any = await this.services.updateRentRelationGoods(params);
    this.subRelationGoodLoading = false;

    if (res.code === 0) {
      this.msg.success('操作成功');
      this.isRelationVisible = false;
      this.loadTable();
    } else {
      this.msg.error(res.message);
    }
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  // 控制是否显示二级目录
  onTableOneItem(item: any) {
    const { list } = item;
    if (!list || list.length <= 0) {
      return
    }
    item.isShow = !item.isShow;
  }

  // 控制是否显示三级级目录
  onTableSecondItem(item: any) {
    const { list } = item;
    if (!list || list.length <= 0) {
      return
    }
    item.isShow = !item.isShow;
  }

  status_to_text(val: number) {
    const text: any = { 0: '禁用', 1: '启用' };
    return text[val] || '-';
  }

  userType_to_text(val: number) {
    const text: any = { 0: '通用', 1: 'C端', 2: 'B端' };
    return text[val] || '-';
  }

  // 跳转方式 code转换中文
  type_to_text(val: number) {
    return this.typeSet[val] || '-'
  }
}
